// pages/cart/cart.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        totalNum:0,
        orderURL: '/', //结算跳转
        cartSwitch: true, // 编辑开关
        totalPrice: 0, // 总价，初始为0
        allChecked: false, // 全选状态，默认不选
        shopping_car_ids:[],//购物车合集
        address_id:"", //地址id
        listdata: '',
        cart: [
        //     {
        //     num: 1,
        //     lu_id: 1,
        //     checked: false,
        //     lu_price: '168.00',
        //     lu_name: "泸宝原窖升30",
        //     lu_capacity: "500ml/瓶",
        //     lu_small_logo: "//img12.360buyimg.com/ddimg/jfs/t1/129153/40/13064/11623/5f686469E80548dde/6dafd0493211c445.png",
        // }, {
        //     num: 1,
        //     lu_id: 2,
        //     checked: false,
        //     lu_price: '188.00',
        //     lu_name: "泸宝原窖经典",
        //     lu_capacity: "500ml/瓶",
        //     lu_small_logo: "//img11.360buyimg.com/ddimg/jfs/t1/127912/16/13040/11234/5f686469E6af166e0/15f1038b13a29556.png",
        // }, {
        //     num: 1,
        //     lu_id: 3,
        //     checked: false,
        //     lu_price: '198.00',
        //     lu_name: "泸宝原窖红典",
        //     lu_capacity: "500ml/瓶",
        //     lu_small_logo: "//img14.360buyimg.com/ddimg/jfs/t1/154191/13/457/11044/5f686469E5374cda9/31ad5f49de0cce19.png",
        // }
    ]
    },
    //编辑模式
    // cartSwitch() {
    //     let cartSwitch = this.data.cartSwitch;
    //     cartSwitch = !cartSwitch;
    //     this.setData({
    //         cartSwitch: cartSwitch,
    //     })
    // },
    // 增加数量
    addCount(e) {
        const index = e.currentTarget.dataset.index;
        let cart = this.data.cart;
        let num = cart[index].num;
        num = num + 1;
        cart[index].num = num;
        this.setData({
            cart: cart
        });
        this.getTotalPrice();
    },
    // 减少数量
    minusCount(e) {
        const index = e.currentTarget.dataset.index;
        let cart = this.data.cart;
        let num = cart[index].num;
        if (num <= 1) {
            return false;
        }
        num = num - 1;
        cart[index].num = num;
        this.setData({
            cart: cart
        });
        this.getTotalPrice();
    },
    // 商品的选中
    handeItemChange(e) {
        // 1 获取被修改的商品的id
        // console.log(e);
        
        const lu_id = e.target.dataset.id;
        // 2 获取购物车数组 
        let cart = this.data.cart;
        // 3 找到被修改的商品对象
        let index = cart.findIndex(v => v.shopping_car_id === lu_id);
        // 4 选中状态取反
        cart[index].checked = !cart[index].checked;
        this.setCart(cart);
        this.getTotalPrice(); // 重新获取总价
    },
    setCart(cart) {
        let allChecked = true;
        // 1 总价格 总数量
        let totalPrice = 0;
        let totalNum = 0;
        let aa = [];
        cart.forEach(v => {
                if (v.checked) {
                    totalPrice += v.num * v.sku.price;
                    totalNum += v.num;
                    aa.push(v)
                } else {
                    allChecked = false;
                }
            })
            // 判断数组是否为空
        allChecked = cart.length != 0 ? allChecked : false;
        this.setData({
            cart,
            totalPrice,
            totalNum,
            allChecked,
        });
        this.getTotalPrice(); // 重新获取总价
        wx.setStorageSync("cart", cart);
        wx.setStorageSync('cartLen', cart.length);
    },
    // 商品全选功能
    handleItemAllCheck() {
        // 1 获取data中的数据
        let { cart, allChecked } = this.data;
        // 2 修改值
        allChecked = !allChecked;
        // 3 循环修改cart数组 中的商品选中状态
        cart.forEach(v => v.checked = allChecked);
        // 4 把修改后的值 填充回data或者缓存中
        this.setCart(cart);
        this.getTotalPrice(); // 重新获取总价
    },
    getTotalPrice() {
        let cart = this.data.cart; // 获取购物车列表
        let total = 0;
        let totalNum = 0;
        for (let i = 0; i < cart.length; i++) { // 循环列表得到每个数据
            if (cart[i].checked) { // 判断选中才会计算价格
                total += cart[i].num * cart[i].sku.price; // 所有价格加起来
                totalNum += cart[i].num;
                this.data.shopping_car_ids.push(cart[i].shopping_car_id)
            }else{
                this.data.shopping_car_ids.splice(i,1) 
            }
        }
        let goods = [];
        cart.forEach(v => goods.push({
            goods_id: v.good_id,
            goods_number: v.num,
            goods_price: v.sku.price
        }))
        wx.setStorageSync('goods', goods);
        this.setData({ // 最后赋值到data中渲染到页面
            cart: cart,
            totalNum: totalNum,
            totalPrice: total.toFixed(2)
        });
    },
    deleteList(e) {
        const index = e.currentTarget.dataset.index;
        let cart = this.data.cart;
        let ii = wx.getStorageSync('ii');
        if(ii){
            ii.forEach(item =>{
                wx.request({//删除购物车列表
                    url: 'http://api_dev.wanxikeji.cn/api/shoppingCarDelete',
                    method:'POST',
                    data: {
                        token:wx.getStorageSync("token"),
                        shopping_car_id:item
                    },
                    success: (res) => {
                    }
                })   
            })     
        }
        wx.request({
            url: 'http://api_dev.wanxikeji.cn/api/shoppingCarDelete',
            method:'POST',
            data: {
                token:wx.getStorageSync("token"),
                shopping_car_id:this.data.cart[index].shopping_car_id
            },
            success: (res) => {
                // console.log(res);
            }
        });
        cart.splice(index, 1); // 删除购物车列表里这个商品
        wx.setStorageSync('cartLen', cart.length);
        let app = getApp()
        app.scanCart(this)
        this.setData({
            cart: cart
        });
        if (!cart.length) { // 如果购物车为空
            this.setData({
                hasList: false, // 修改标识为false，显示购物车为空页面
            });
            this.getTotalPrice(); // 重新获取总价
            this.handleItemAllCheck();
        } else {
            this.getTotalPrice(); // 重新计算总价格
        }
    },
    orderURL() { //页面跳转
        let cart = this.data.cart;
        if (cart.length) { // 如果购物车不为空
            cart.forEach(v => {
                if (v.checked) {
                    wx.request({
                        url: 'http://api_dev.wanxikeji.cn/api/generateOrder',
                        method:'POST',
                        data: {
                            token:wx.getStorageSync("token"),
                            address_id:this.data.address_id,
                            money:this.data.totalPrice,
                            shopping_car_ids:this.data.shopping_car_ids,
                        },
                        success: (res) => {
                            // console.log(res,666666666);
                        }
                    });
                    let bb = [];
                    bb = {
                        address_id:this.data.address_id,
                        shopping_car_ids:this.data.shopping_car_ids
                    }
                    wx.setStorageSync('bb', bb)
                    wx.setStorageSync('cartLen', cart.length);
                    wx.navigateTo({
                        url: '/pages/orders/orders',
                    });
                }
            })
        }
    },
    
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.setData({
            cart:wx.getStorageSync('cart')
        })
        wx.showToast({title: '加载中', icon: 'loading', duration: 10000});
        var that = this;
        wx.request({
            url: 'http://api_dev.wanxikeji.cn/api/userAddressList',
            method:'POST',
            data: {
                token:wx.getStorageSync("token"),
            },
            success: (res) => {
                // console.log(res);
                that.setData({
                    address_id:res.data.data[0].address_id
                });
            }
        });
        wx.request({//模拟购物车列表
            url: 'http://api_dev.wanxikeji.cn/api/shoppingCarList',
            method:'POST',
            data: {
                token: wx.getStorageSync("token"),
            },
            success: (res) => {
                // console.log(res);
                let a = [];
                a = res.data.data.data;
                let app = getApp()
                app.scanCart(that)
                //去重
                var hash = [];
                var ii = [];
                a = a.reduce(function(x, y,index,arr) {
                    if(hash[y['sku']]){
                        ii.push(y.shopping_car_id);
                        wx.setStorageSync('ii', ii);
                        arr.forEach(item=>{
                            if(item.sku==y.sku){
                                item.num++;
                            }
                        });
                        
                    }
                    hash[y['sku']] ? '' : hash[y['sku']] = true && x.push(y);
                    return x;
                }, []);
                wx.setStorageSync('cartLen', a.length);
                a.forEach((i,index)=>{
                    let flag = false;
                    if(a.includes(i.goods)){
                        console.log(11);
                    }
                    if (i.sku){
                        i.sku = JSON.parse(i.sku);
                    }
                    i.checked = false;
                })
                this.setData({
                    cart:a
                })
                wx.hideToast();
                // console.log(this.data.cart);
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        wx.showToast({title: '加载中', icon: 'loading', duration: 10000});
        wx.request({
            url: 'http://api_dev.wanxikeji.cn/api/userAddressList',
            method:'POST',
            data: {
                token:wx.getStorageSync("token"),
            },
            success: (res) => {
                this.setData({
                    address_id:res.data.data[0].address_id
                });
            }
        });
        this.setData({
            cart:wx.getStorageSync('cart')
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})